<template>
  <el-form ref="formRef" :model="_form" :rules="rules" label-width="100px" size="small">
    <div v-if="!isAdd" class="top">
      <div class="top-l">
        <el-form-item label-width="0">
          <hold-upload
            :key="uploadKey"
            list-type="picture"
            :file-list="[]"
            :limit="1"
            file-name="headPhoto"
            file-type=".png,.jpg,.jpeg"
            :show-file-list="false"
            :avatar-url="_form.headPhoto ? formatUrl(_form.headPhoto) : ''"
            @success="handleSuccess"
          />
        </el-form-item>
      </div>
    </div>
    <el-form-item label="登录账号" class="account-item" prop="loginCode">
      <el-input v-model="_form.loginCode" :disabled="!isAdd" placeholder="请输入登录账号" />
    </el-form-item>
    <el-form-item label="姓名" prop="name">
      <el-input v-model="_form.name" placeholder="请输入姓名" />
    </el-form-item>
    <el-form-item label="手机号" prop="phone">
      <el-input v-model.trim="_form.phone" placeholder="请输入手机号" />
    </el-form-item>
    <!-- <el-form-item label="组" prop="groups">
      <el-select v-model="_form.groups" multiple placeholder="请选择组" clearable filterable>
        <el-option
          v-for="item in state.groupOptions"
          :key="item.gid"
          :label="item.name"
          :value="item.gid"
        />
      </el-select>
    </el-form-item>-->
    <!-- <el-form-item label="系统权限" prop="sysRole">
      <el-select v-model="_form.sysRole" placeholder="请选择系统权限" clearable filterable>
        <el-option
          v-for="item in roleData.sysRole"
          :key="item.rid"
          :label="item.name"
          :value="item.rid"
        />
      </el-select>
    </el-form-item>-->
    <el-form-item label="角色" prop="role">
      <el-select v-model="_form.role" multiple placeholder="请选择角色" clearable filterable>
        <el-option
          v-for="item in roleData.defRole"
          :key="item.rid"
          :label="item.name"
          :value="item.rid"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="邮箱" prop="email">
      <el-input v-model.trim="_form.email" placeholder="请输入邮箱" />
    </el-form-item>
    <el-row>
      <el-col :span="12">
        <el-form-item label="出生日期" prop="birthday">
          <el-date-picker
            v-model="_form.birthday"
            value-format="YYYY-MM-DD"
            type="date"
            placeholder="选择日期"
            :disabled-date="disabledDate"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="性别" prop="gender">
          <el-select v-model="_form.gender" placeholder="性别" clearable>
            <el-option
              v-for="item in sexOptions"
              :key="item.name"
              :label="item.name"
              :value="item.name"
            />
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>

    <el-form-item>
      <div class="btn-operators">
        <el-button class="cancel" @click="cancel">取消</el-button>
        <el-button type="primary" class="save" :loading="saveLoading" @click="confrim">{{
          saveLoading ? '' : '保存'
        }}</el-button>
      </div>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { computed, defineEmits, defineExpose, defineProps, reactive, ref, toRefs, watch } from 'vue'

import { ElMessage } from 'element-plus'

import HoldUpload from '@/components/Upload/index.vue'

import GroupApi from '@/api/backend/group'
import UserApi from '@/api/backend/user'

import { useUserStore } from '@/store/user'

import { formatUrl } from '@/utils/common/formatUrl'
import { commonAccountReg, commonContactReg, emailReg, phoneReg } from '@/utils/regExp'

import IBaseObj from '#/index'

const { userInfo, updateUserInfo } = useUserStore()

const disabledDate = (time: Date) => {
  return time.getTime() > Date.now()
}

const rules = {
  // groups: [
  //   {
  //     type: 'array',
  //     required: true,
  //     message: '请选择组',
  //     trigger: 'change'
  //   }
  // ],
  // sysRole: [{ required: true, message: '请选择系统权限', trigger: 'change' }],
  // role: [{ required: true, message: '请选择角色', trigger: 'change' }],
  loginCode: [
    { required: true, message: '请输入登录账号', trigger: 'blur' },
    { max: 20, message: '输入长度超过20个字符', trigger: 'blur' },
    {
      ...commonAccountReg,
      trigger: 'blur',
    },
    // { validator: checkloginCode, trigger: 'blur' }
  ],
  name: [
    {
      required: true,
      message: '请输入姓名',
      trigger: 'blur',
    },
    { max: 20, message: '输入长度超过20个字符', trigger: 'blur' },
    {
      pattern: commonContactReg.pattern,
      message: commonContactReg.message,
      trigger: 'blur',
    },
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { ...phoneReg, trigger: 'blur' },
    // { validator: checkPhone, trigger: 'blur' }
  ],
  email: [
    // { required: true, message: '请输入邮箱', trigger: 'blur' },
    { ...emailReg, trigger: 'blur' },
    // { validator: checkEmail, trigger: 'blur' }
  ],
}

const sexOptions = [
  {
    name: '男',
  },
  {
    name: '女',
  },
]

const props = defineProps({
  form: {
    type: Object,
    default: () => {},
  },
  isAdd: {
    type: Boolean,
    default: true,
  },
  roleData: {
    type: Object,
    default: () => {
      return {
        // sysRole: [],
        defRole: [],
      }
    },
  },
})

const emits = defineEmits(['update:form', 'cancel', 'confirm'])

const _form = computed({
  get() {
    return props.form
  },
  set() {
    emits('update:form')
  },
})

const state: IBaseObj = reactive({
  saveLoading: false,
  uploadKey: +new Date(),
  groupOptions: [],
  currentHeadPhoto: '',
})

const { saveLoading, uploadKey } = toRefs(state)

watch(
  () => props.isAdd,
  (val) => {
    if (!val) {
      state.currentHeadPhoto = _form.value.headPhoto
    }
  },
  {
    immediate: true,
  }
)

const getGroupData = async () => {
  const ret = await GroupApi.getGlobalGroups()
  state.groupOptions = ret.data || []
}
getGroupData()

const cancel = () => {
  emits('cancel')
}

const formRef = ref()
const confrim = () => {
  formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      state.saveLoading = true
      try {
        const res = await UserApi.saveUser({ ..._form.value })
        const { status } = res
        if (status === 200) {
          if (props.isAdd) {
            ElMessage({ message: '创建成功!', type: 'success', duration: 1500 })
          } else {
            ElMessage({ message: '修改成功!', type: 'success', duration: 1500 })
            if (state.currentHeadPhoto !== _form.value.headPhoto) {
              // 创建了头像
              updateInfo()
            }
          }
          emits('confirm')
        }
      } catch (error) {
        console.log(error)
      } finally {
        state.saveLoading = false
      }
    } else {
      return false
    }
  })
}

const clear = () => {
  formRef.value.resetFields()
  state.currentHeadPhoto = ''
}

const handleSuccess = (file: any) => {
  _form.value.headPhoto = file.file.prepareData
}

const updateInfo = () => {
  // 如果创建的是本人的
  if (_form.value.uid === userInfo.uid) {
    const currentInfo = { ...userInfo }
    currentInfo.headPhoto = _form.value.headPhoto
    updateUserInfo(currentInfo)
  }
}

defineExpose({
  clear,
})
</script>

<style lang="scss" scoped>
.role-item {
  .el-select {
    width: 100% !important;
  }
}

.top {
  display: flex;
  justify-content: center;
  width: 100%;

  &-l {
    :deep(.el-form-item__content) {
      width: auto;
    }
  }

  &-r {
    margin-left: 10px;
    color: white;
    flex: 1;

    :deep(.el-form-item) {
      width: 100%;

      .el-form-item__content {
        width: auto;
      }
    }
  }
}
</style>
